package com.yijietong.yiliao.doctor.controller;

import com.alibaba.fastjson.JSONObject;
import com.easemob.server.api.impl.EasemobChatGroup;
import com.easemob.server.api.impl.EasemobIMUsers;
import com.google.gson.Gson;
import com.yijietong.yiliao.doctor.pojo.GroupBean;
import com.yijietong.yiliao.doctor.bean.SmsVerifyBean;
import com.yijietong.yiliao.doctor.network.api.ApiStore;
import com.yijietong.yiliao.doctor.network.api.ApiStoreManage;
import com.yijietong.yiliao.doctor.pojo.BaseBean;
import com.yijietong.yiliao.doctor.pojo.User;
import com.yijietong.yiliao.doctor.pojo.UserLogin;
import com.yijietong.yiliao.doctor.pojo.UserToken;
import com.yijietong.yiliao.doctor.service.IUserService;
import com.yijietong.yiliao.doctor.utils.EncryptUtils;
import com.yijietong.yiliao.doctor.utils.RegexUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import retrofit2.Call;

import javax.annotation.Resource;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    private Gson gson = new Gson();

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public BaseBean<User> addUser(@RequestParam(value = "phone") String phone,
                                  @RequestParam(value = "password") String password,
                                  @RequestParam(value = "code") String code) {
        BaseBean<User> baseBean = new BaseBean<>();
        if (RegexUtils.isMobileSimple(phone)) {
            try {
                User user = this.userService.getUserByPhone(phone);
                if (user == null) {
                    if (password == null || password.length() == 0) {
                        baseBean.setCode(2011);
                        baseBean.setMessage("注册失败，密码不能为空");
                    } else if (password.length() < 6 || password.length() > 25) {
                        baseBean.setCode(2012);
                        baseBean.setMessage("密码长度需要为6-25位");
                    } else {
                        //验证短信
                        ApiStore apiStoreSMS = ApiStoreManage.getApiStoreSMS();
                        Call<SmsVerifyBean> call = apiStoreSMS.verrifyCode("2244b7122b740", phone, "86", code);
                        SmsVerifyBean body = call.execute().body();

                        if (body != null && body.getStatus() == 200) {
                            //添加用户
                            EasemobIMUsers easemobIMUsers = new EasemobIMUsers();
                            io.swagger.client.model.RegisterUsers usersHx = new io.swagger.client.model.RegisterUsers();
                            io.swagger.client.model.User userHx = new io.swagger.client.model.User();
                            userHx.setUsername(phone);
                            userHx.setPassword(password);
                            usersHx.add(userHx);
                            String userCreate = (String) easemobIMUsers.createNewIMUserSingle(usersHx);

                            int count = 0;
                            if (userCreate != null) {
                                // 环信注册成功.写入新用户。
                                user = new User();
                                user.setPassword(password);
                                user.setPhone(phone);
                                long currentTimeMillis = System.currentTimeMillis();
                                user.setUserId(EncryptUtils.encryptMD5ToString(currentTimeMillis + phone));
                                user.setCreated(currentTimeMillis);
                                user.setModified(currentTimeMillis);
                                user.setActivated(currentTimeMillis);
                                user.setUsername("");

                                User userByPhone = userService.getUserByPhone(phone);
                                if (userByPhone == null) {
                                    // 新增用户。
                                    count = userService.addUser(user);
                                } else {
                                    // 如果已经存在，除创建时间和用户ID外，全部内容更新。
                                    user.setCreated(userByPhone.getCreated());
                                    user.setUserId(userByPhone.getUserId());
                                    count = userService.updateUser(user);
                                }
                            } else {
                                // 环信注册失败，服务器内不写入，0条代表注册失败。
                                count = 0;
                            }

                            if (count > 0) {
                                //不用返回给APP  baseBean.setData(user);
                                baseBean.setCode(0);
                                baseBean.setMessage("注册成功");
                            } else {
                                baseBean.setCode(201);
                                baseBean.setMessage("注册失败");
                            }
                        } else {
                            if (body == null || body.getStatus() == 0) {
                                baseBean.setCode(210);
                                baseBean.setMessage("短信验证码错误，请重新输入。");
                            } else {
                                baseBean.setCode(body.getStatus());
                                switch (body.getStatus()) {
                                    case 467:
                                        baseBean.setMessage("短信验证码已经失效，请重新获取。");
                                        break;
                                    case 468:
                                        baseBean.setMessage("短信验证码错误，请重新输入。");
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }

                    }
                } else {
                    baseBean.setCode(202);
                    baseBean.setMessage("该用户已存在，请更改手机号码再试");
                }
            } catch (Exception e) {
                e.printStackTrace();
                baseBean.setCode(203);
                baseBean.setMessage("注册失败" + e.getMessage());
            }
        } else {
            baseBean.setCode(204);
            baseBean.setMessage("请输入正确的手机号码");
        }
        return baseBean;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public BaseBean<UserLogin> login(@RequestParam(value = "phone") String phone,
                                     @RequestParam(value = "password") String password) {
        BaseBean<UserLogin> baseBean = new BaseBean<>();
        if (RegexUtils.isMobileSimple(phone)) {
            try {
                User user = this.userService.getUserByPhone(phone);
                if (user == null) {
                    baseBean.setCode(205);
                    baseBean.setMessage("手机号和密码不匹配，请重新输入");
                } else if (password != null && password.equals(user.getPassword())) {
                    // 登录成功，插入一条新增token的数据。
                    long currentTimeMillis = System.currentTimeMillis();
                    UserToken userToken = new UserToken();
                    userToken.setCreated(currentTimeMillis);
                    String token = EncryptUtils.encryptMD5ToString(currentTimeMillis + phone);
                    userToken.setToken(token);
                    userToken.setUserId(user.getUserId());
                    int count = userService.insertToken(userToken);

                    if (count > 0) {
                        //TODO：去查询用户资料，再返回。
                        UserLogin userLogin = new UserLogin();
                        userLogin.setToken(token);
                        userLogin.setPhone(user.getPhone());
                        userLogin.setUserId(user.getUserId());
                        userLogin.setUsername(user.getUsername() == null ? "" : user.getUsername());

                        baseBean.setData(userLogin);
                        baseBean.setCode(0);
                        baseBean.setMessage("登录成功");
                    } else {
                        baseBean.setCode(501);
                        baseBean.setMessage("服务器异常");
                    }
                } else {
                    baseBean.setCode(206);
                    baseBean.setMessage("手机号与密码不匹配，请重新输入");
                }
            } catch (Exception e) {
                e.printStackTrace();
                baseBean.setCode(207);
                baseBean.setMessage("登录失败");
            }
        } else {
            baseBean.setCode(204);
            baseBean.setMessage("请输入正确的手机号码");
        }
        return baseBean;
    }

    @RequestMapping(value = "/createGroup", method = RequestMethod.POST)
    @ResponseBody
    public BaseBean createGroup(@RequestParam(value = "groupName") String groupName,
                                @RequestParam(value = "desc") String desc,
                                @RequestParam(value = "owner") String owner) {
        BaseBean baseBean = new BaseBean<>();
        baseBean.setCode(201);
        EasemobChatGroup easemobChatGroup = new EasemobChatGroup();
        GroupBean group = new GroupBean();
        group.setDesc(desc);
        group.setGroupname(groupName);
        group.setApproval(true); // 猜：是否需要群主或管理员批准。
        group.setOwner(owner);//群主？群管理？
        group.setMaxusers(500);//群组最大人数
        group.setPublic(true); // 是否公开群。
        String chatGroup = (String) easemobChatGroup.createChatGroup(group);
        if(chatGroup!=null) {
            JSONObject parse = (JSONObject) JSONObject.parse(chatGroup);
            if(parse!=null) {
                JSONObject data = parse.getJSONObject("data");
                if (data != null) {
                    String groupId = data.getString("groupid");
                    if (groupId != null) {
                        // TODO:保存到数据库中。
                        //userService.getUserByUserId()
                        group.setGroupId(groupId);
                        baseBean.setCode(0);
                        baseBean.setMessage("创建群组成功");
                        baseBean.setData(group);
                    }
                }
            }
        }

        if(baseBean.getCode()!=0){
            baseBean.setCode(210);
            baseBean.setMessage("创建群组失败");
            baseBean.setData(null);
        }

        return baseBean;
    }
}
